﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Core
{
    public class PointerClickListener : MonoBehaviour,
        IPointerClickHandler,
        IPointerDownHandler,
        IPointerUpHandler
    {
        public event Action OnDown;
        public event Action OnUp;
        public event Action OnClick;

        private bool isDown = false;

        public static PointerClickListener Get(GameObject go)
        {
            return go.GetComponent<PointerClickListener>() ??
                   go.AddComponent<PointerClickListener>();
        }

        public static PointerClickListener Get(UIWidget widget)
        {
            return Get(widget.gameObject);
        }

        public void Reset()
        {
            isDown = false;
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            // onClick?.Invoke(gameObject);
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            // log.err("OnPointerDown");
            if (isDown) return;

            OnDownHandler();
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            // log.err("OnPointerUp");
            if (isDown == false) return;

            OnUpHandler();
        }

        private void OnDownHandler()
        {
            isDown = true;
            // log.err("OnDownHandler");

            OnDown?.Invoke();
        }

        private void OnUpHandler()
        {
            // log.err("OnUpHandler");

            isDown = false;
            OnUp?.Invoke();
            OnClick?.Invoke();
        }
    }
}